// 设置为全局变量
window.API_CONFIG = {
    BASE_URL: 'http://localhost:8000/api',
    TOKEN_KEY: 'access_token',
    USER_KEY: 'user'
};

// API 请求工具，设置为全局变量
window.apiClient = axios.create({
    baseURL: window.API_CONFIG.BASE_URL,
    headers: {
        'Content-Type': 'application/json'
    }
});

// 请求拦截器，自动添加 token
window.apiClient.interceptors.request.use(
    (config) => {
        const token = localStorage.getItem(window.API_CONFIG.TOKEN_KEY);
        if (token) {
            config.headers.Authorization = `Bearer ${token}`;
        }
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

// 响应拦截器，处理错误
window.apiClient.interceptors.response.use(
    (response) => response,
    (error) => {
        if (error.response?.status === 401) {
            // token 过期或无效，清除本地存储并跳转到登录页
            localStorage.removeItem(window.API_CONFIG.TOKEN_KEY);
            localStorage.removeItem(window.API_CONFIG.USER_KEY);
            window.location.href = '/index.html';
        }
        return Promise.reject(error);
    }
); 